package com.jack.leetcode.每日一题;

import java.util.*;

/***
 * @author zhangjie
 * @date 2020/4/16 20:30
 */
public class 合并区间 {

    public static void main(String[] args) {
        int[][] v = {{1,3},{2,6},{8,10},{15,18}};
        int[][] result = merge(v);
        for(int i=0;i<result.length;i++){
            for(int j=0;j<result[0].length;j++){
                System.out.print(result[i][j]);
                System.out.println(" ");
            }
            System.out.println();
        }
    }

    public static int[][] merge(int[][] intervals) {
        Arrays.sort(intervals,(v1,v2)->v1[0]-v2[0]);
        int m = intervals.length;
        if(m<2){
            return intervals;
        }
        List<int[]> list = new ArrayList<>();
        list.add(intervals[0]);
        for (int i = 1; i < m; i++) {
            int[] cur = intervals[i];
            int[] peek = list.get(list.size() - 1);
            if(cur[0] > peek[1]){
                list.add(cur);
            }else{
                peek[1] = Math.max(cur[1],peek[1]);
            }
        }
        return list.toArray(new int[list.size()][2]);
    }
}
